package com.zcj.demo.config;

import com.zcj.demo.user.service.UserService;
import com.zcj.demo.user.service.dto.UserDTO;
import com.zcj.demo.web.user.vo.UserVO;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author: 68300119
 * @Date 2021/3/1
 **/
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权----doGetAuthorizationInfo");
        UserDTO user = (UserDTO) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(user.getAccess());
        return info;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证----doGetAuthenticationInfo");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        UserVO userVO = new UserVO();
        userVO.setUsername(token.getUsername());
        UserDTO user = userService.findAll(userVO).get(0);
        if (null == user) {
            // 抛出UnknownAccountException
            return null;
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }
}
